import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/en' // lang i18n
import * as echarts from 'echarts'; 
import '@/styles/index.scss'

import App from './App'
import store from './store'
import router from './router'

import '@/icons' // icon
// import '@/permission' // permission control
import { getRoleJson, _getRoleList } from '../src/utils/permission'
import { asyncRouterMap } from '../src/router/index'

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
if (process.env.NODE_ENV === 'production') {
  const { mockXHR } = require('../mock')
  mockXHR()
}

// set ElementUI lang to EN
Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui，按如下方式声明
// Vue.use(ElementUI)


Vue.prototype.$echarts = echarts

Vue.config.productionTip = false

router.beforeEach(async (to, from, next) => {
  if (to.path.toLowerCase() == "/login") {
    //判断 路径是不是login  如果是的话 直接放行
    next();
  }
  else if (to.path == "/register") {
    next();
  }
  else {
    let { state, commit } = store;
    // 如果添加过直接next()
    if (state.isAddRouter) {
      next();
    }
    // 如果没添加
    else {
      try {
        // 从本地获取token 
        let token = localStorage.getItem("Jurisdiction");
        console.log(token,"token________main");
        if (token) {
          // 从接口获取权限列表
          let roleList = await getRoleJson(token);
          // roleList 得到的是对应角色的路由表
          // _getRoleList 接收两个参数：
          // asyncRouterMap 是完整的路由表
          // roleList 是当前角色能够访问到的路由
          let list = _getRoleList(asyncRouterMap, roleList);
          // list 动态的路由
          // console.log("控制权限", list);
          
          router.addRoutes(list);
          // 改变状态，表示已经配置过权限
          commit("update", { name: "isAddRouter", value: true });
          // 把筛选后的权限存入vuex里，用于渲染左侧菜单
          commit("update", { name: "asyncRoutes", value: list });
          next({ path: list[0].children[0].path });
          
        } else {
          next({ path: "/login" });
        }
      } catch (e) {

        next({ path: "/login" });
        console.log(e);
      }
    }
  }
});

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
